const express = require('express')
const multer = require('multer')
const fs = require('fs')
const router = express.Router()

const Music = require('../../models/Music')

router.post('/add', multer({
  dest: 'asset/music'
}).array('file', 10), (req, res) => {
  let files = req.files;
  if (files.length === 0) {
    res.render("error", {message: "上传文件不能为空！"});
    return
  } else {
    let fileInfo = {};
    for (let i in files) {
      let file = files[i];
      fs.renameSync(file.path, `asset/music/${file.originalname}`)
      // req.body.url = req.file.originalname
      // req.body.url ? res.download(`asset/music/${req.body.url}`) : res.send({
      //     success: false
      // })
      console.log(file)
      if (file.mimetype.indexOf('image') !== -1) {
        fileInfo.photo = 'http://localhost:5000/api/music/musicInf?url=' + file.originalname
      } else {
        fileInfo.music = 'http://localhost:5000/api/music/musicInf?url=' + file.originalname
      }
    }
    fileInfo.song = req.body.song
    fileInfo.singer = req.body.singer
    fileInfo.album = req.body.album
    new Music(fileInfo).save().then(music => {
      res.json(music)
    })
  }
})


router.get('/musicInf', (req, res) => {
  req.query.url ? res.download(`asset/music/${req.query.url}`) : res.send({
    success: false
  })
})

//查询音乐
router.get('/', (req, res) => {
  Music.find()
    .then(music => {
      if (!music) {
        return res.status(404).json('没有任何内容')
      }
      res.json(music)
    })
    .catch(err => res.status(404).json(err))
})

//修改喜欢
router.get('/love/:id', (req, res) => {
  Music.update({
    _id: req.params.id
  }, {
    $set: {
      like: req.query.like
    }
  }, err => {
    if (err) {
      console.log(err);
    }
  }).then(() => res.json('ok'))
})

module.exports = router